package org.changs.nav.mvp;

import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Tip;

import org.changs.aplug.base.BasePresenter;
import org.changs.nav.delegate.amap.AmapRouteHelper;
import org.changs.nav.delegate.amap.AmapSearchHelper;
import org.changs.nav.delegate.amap.AmapTipHelper;

import java.util.ArrayList;

import javax.inject.Inject;

import aplug.data.db.SearchRecordHelper2;
import aplug.data.db.mode.SearchRecord;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yincs on 2017/10/14.
 */

public class SearchPresenter extends BasePresenter<SearchContract.V> implements SearchContract.P {

    private final AmapSearchHelper mAmapSearchHelper;
    private final SearchRecordHelper2 mSearchRecordHelper2;
    private final AmapTipHelper mAmapTipHelper;
    private final AmapRouteHelper mAmapRouteHelper;

    @Inject
    public SearchPresenter(AmapSearchHelper amapSearchHelper, SearchRecordHelper2 searchRecordHelper2, AmapTipHelper amapTipHelper, AmapRouteHelper amapRouteHelper) {
        mAmapSearchHelper = amapSearchHelper;
        mSearchRecordHelper2 = searchRecordHelper2;
        mAmapTipHelper = amapTipHelper;
        mAmapRouteHelper = amapRouteHelper;
    }

    @Override
    public void initState(int state) {
        if (isDetachView()) return;
        if (state == SearchContract.STATE_MAIN) {
            getMvpView().showMainView();
            loadMainRecord();
        } else if (state == SearchContract.STATE_SEARCHING) {
            getMvpView().showSearchView();
            loadSearchRecord();
        } else {
            getMvpView().showMoreView();
        }
    }

    @Override
    public void loadMainRecord() {
        mSearchRecordHelper2.getAllPoiSearchRecord()
                .filter(searchRecords -> searchRecords.size() > 0)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(searchRecords -> {
                    if (isDetachView()) return;
                    getMvpView().showMainRecordList(searchRecords);
                });
    }

    @Override
    public void loadSearchRecord() {
        mSearchRecordHelper2.getAllSearchRecord()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(searchRecords -> {
                    if (isDetachView()) return;
                    getMvpView().showSearchRecordList(searchRecords);
                });
    }

    @Override
    public void loadTip(String key) {
        mAmapTipHelper.query(key, list -> {
            if (isDetachView()) return;
            getMvpView().showSearchTip(list);
        });
    }

    @Override
    public void clickTip(Tip tip) {
        LatLonPoint latLonPoint = tip.getPoint();
        if (latLonPoint == null) {
            clickSearchPoi(tip.getName());
            return;
        }
        getMvpView().showLoading().setMessage("路线规划中...")
                .cancelAction(mAmapRouteHelper::cancel);
        mSearchRecordHelper2.insertOrUpdateSearchRecord(SearchRecord.poi(tip.getName(), tip.getAddress(),
                -1, latLonPoint.getLatitude(), latLonPoint.getLongitude()))
                .subscribeOn(Schedulers.io())
                .subscribe();
        mAmapRouteHelper.calculate(new NaviLatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude()),
                new ArrayList<>(), new AmapRouteHelper.AMapNaviListener() {
                    @Override
                    public void onError(int code, String msg) {
                        if (isDetachView()) return;
                        getMvpView().onError("路线规划失败 " + code);
                        getMvpView().hideLoading();
                    }

                    @Override
                    public void onSuccess(int[] ints) {
                        getMvpView().startRouteView(tip, ints);
                    }
                });
    }


    @Override
    public boolean onBackPressed(@SearchContract.State int state) {
        if (state != SearchContract.STATE_MAIN) {
            initState(SearchContract.STATE_MAIN);
            return true;
        }
        return false;
    }

    @Override
    public void clickSearchPoi(String keyword) {
        getMvpView().showLoading()
                .setMessage("正在搜索中")
                .cancelAction(mAmapSearchHelper::cancel);

        mSearchRecordHelper2
                .insertOrUpdateSearchRecord(SearchRecord.normal(keyword))
                .subscribeOn(Schedulers.io())
                .subscribe();

        mAmapSearchHelper.search(keyword, new AmapSearchHelper.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(ArrayList<PoiItem> poiItems) {
                if (isDetachView()) return;
                getMvpView().startPoiListView(poiItems);
            }

            @Override
            public void onError(int code, String msg) {
                if (isDetachView()) return;
                getMvpView().onError("搜索失败 " + code);
                getMvpView().hideLoading();
            }
        });
    }

    @Override
    public void clearRecord() {
        mSearchRecordHelper2.clearSearchRecord()
                .subscribe(success -> {
                    if (!success || isDetachView()) return;
                    getMvpView().showMainView();
                });
    }

    @Override
    public void clickRecord(SearchRecord record) {
        Tip tip = new Tip();
        if (record.getType() == SearchRecord.TYPE_POI) {
            tip.setName(record.getName());
            tip.setAddress(record.getAddress());
            tip.setPostion(new LatLonPoint(record.getLatitude(), record.getLongitude()));
        } else {
            tip.setName(record.getName());
        }
        clickTip(tip);
    }

    @Override
    public void clickSearchAround(String keyword) {
        getMvpView().showLoading()
                .setMessage("正在搜索中")
                .cancelAction(mAmapSearchHelper::cancel);

        mAmapSearchHelper.searchAround(keyword, new AmapSearchHelper.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(ArrayList<PoiItem> poiItems) {
                if (isDetachView()) return;
                getMvpView().startPoiListView(poiItems);
            }

            @Override
            public void onError(int code, String msg) {
                if (isDetachView()) return;
                getMvpView().onError("搜索失败 " + code);
                getMvpView().hideLoading();
            }
        });
    }
}
